package com.example.demo.redis;

import com.example.demo.util.JsonAndBean;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

@Component
public class RedisServer {
    @Autowired
    JedisPool jedisPool;

    @Autowired
    JsonAndBean jsonAndBean;

    //从redis中取出值
    public <T> T get(BaseRedis baseRedisPrefix,String suffix,Class<T> tClass ) throws JsonProcessingException {
        Jedis jedis=null;
        try {
            //key为自定义的前缀加上数据中查找的后缀
            jedis = jedisPool.getResource();
            String key=baseRedisPrefix.getPrefix()+suffix;
            //返回redis中存储的value
            String value = jedis.get(key);

            //将value(json)转换为对应的类格式
            T t=null;
            if (value!=null){
                t = jsonAndBean.JsonToBean(value, tClass);
            }
            return t;

        } finally {
            jedis.close();//返回连接池
        }
    }

    //把值存入redis中(转换为类对应的json数据格式存入)
    public <T> String set(BaseRedis baseRedisPrefix,String suffix,T object) throws JsonProcessingException {
        Jedis jedis=null;
        try {
            jedis= jedisPool.getResource();

            String key=baseRedisPrefix.getPrefix()+suffix;

            System.out.println("1111");
            //先将object转换为json
            ObjectMapper objectMapper=new ObjectMapper();
            String value= objectMapper.writeValueAsString(object);

            //获取过期时间
            int expireSeconds= baseRedisPrefix.expireSeconds();
            //??
            if (expireSeconds<=0){
                //说明永不过期
                //存入redis
                String set = jedis.set(key, value);
                return set;
            }else {
                //给存入的redis值设置生存时间
                String setex = jedis.setex(key, expireSeconds, value);
                return setex;
            }
        } finally {
            jedis.close();
        }
    }

    public <T> Long decr(BaseRedis prefix,String suffix){
        Jedis jedis=null;
        try
        {
            jedis = jedisPool.getResource();
            //key
            String key=prefix.getPrefix()+suffix;
            Long decr = jedis.decr(key);
            return decr;
        }finally {
            jedis.close();
        }
    }
}

